//
//  HomeViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/4.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "HomeViewController.h"
#import "topCollectionViewCell.h"
#import "bottomCollectionViewCell.h"
#import "StoneStreetStoreDetailViewController.h"

static NSString * topIndentifer = @"topCollectionViewCell";
static NSString * bottomIndentifer = @"bottomCollectionViewCell";

@interface HomeViewController ()
<UICollectionViewDataSource,UICollectionViewDelegate,BestScrollViewDelegate,BestScrollViewDatasource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;

@property (strong, nonatomic) IBOutlet UIView *topView;
@property (strong, nonatomic) IBOutlet UIView *bottomView;
@property (strong, nonatomic) IBOutlet UICollectionView *topCollectionView;
@property (strong, nonatomic) IBOutlet UICollectionView *bottomCollectionView;
@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property (nonatomic,strong)  NSMutableArray  *companyArray;

@end

@implementation HomeViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _imageArray = [NSMutableArray array];
    _companyArray = [NSMutableArray array];
    [self configurationNavigationAndTabbar];
    [self initViewLayout];
    [self getAdvertiseBanner];
    [self addRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    self.view.backgroundColor = [UIColor colorWithWhite:0.961 alpha:1.000];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 505), NO);
    [self adaptiveViewLayout:self.topView];
    self.topView.layer.cornerRadius = 10*VerticalRatio();
    [self adaptiveViewLayout:self.bottomView];
    
    _headerScroll = [[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 155), NO)];
    [self.scroView insertSubview:_headerScroll belowSubview:_topView];
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    self.topCollectionView.backgroundColor = [UIColor clearColor];
    self.topCollectionView.collectionViewLayout = flowLayout;
    [self.topCollectionView registerNib:[UINib nibWithNibName:topIndentifer bundle:nil] forCellWithReuseIdentifier:topIndentifer];
    self.topCollectionView.dataSource = self;
    self.topCollectionView.delegate = self;
    
    UICollectionViewFlowLayout *hotFlowLayout =[[UICollectionViewFlowLayout alloc]init];
    hotFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    hotFlowLayout.minimumInteritemSpacing = 0;
    hotFlowLayout.minimumLineSpacing = 0;
    self.bottomCollectionView.backgroundColor = [UIColor clearColor];
    self.bottomCollectionView.collectionViewLayout = hotFlowLayout;
    [self.bottomCollectionView registerNib:[UINib nibWithNibName:bottomIndentifer bundle:nil] forCellWithReuseIdentifier:bottomIndentifer];
    self.bottomCollectionView.dataSource = self;
    self.bottomCollectionView.delegate = self;
}

#pragma mark === 中英文切换

- (IBAction)exchangeHandel:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [InternationalControl setUserlanguage:@"en"];
    }else{
        [InternationalControl setUserlanguage:@"zh-Hans"];
    }
  
    NSString * english = InternationalControl(@"切换英文");
    [sender setTitle:english forState:UIControlStateNormal];

    UITabBarItem *tabBarItem1 = [self.tabBarController.tabBar.items objectAtIndex:0];
    UITabBarItem *tabBarItem2 = [self.tabBarController.tabBar.items objectAtIndex:1];
    UITabBarItem *tabBarItem3 = [self.tabBarController.tabBar.items objectAtIndex:2];
    tabBarItem1.title = InternationalControl(@"首页");
    tabBarItem2.title = InternationalControl(@"供应链");
    tabBarItem3.title = InternationalControl(@"我的");
    
    [[ NSNotificationCenter  defaultCenter] postNotificationName:@"changeLanguage" object:self];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getRecommendCompany];
        });
    }];
    [_scroView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.companyArray.count == _totle) {
        [_bottomCollectionView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getRecommendCompany];
        });
    }
    
}


#pragma mark ===  首页企业推荐

-(void)getRecommendCompany{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"page"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryMallStoreRECList withHttpType:@"POST" withTag:GS_GS_queryMallStoreRECList];
}



#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"1" forKey:@"Id"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryAdvertismentById withHttpType:@"POST" withTag:GS_GS_queryAdvertismentById];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == _topCollectionView) {
        return 8;
    }else{
        return _companyArray.count;
    }
}
//定义展示的Section的个数
-(NSInteger)nmumberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView != _topCollectionView) {
        return CGSizeMake(76*VerticalRatio(), 79*VerticalRatio());
    }else{
        return CGSizeMake(76*VerticalRatio(), 95*VerticalRatio());
        
    }
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,0, 0, 0);
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _topCollectionView) {
        topCollectionViewCell * topCell = [collectionView dequeueReusableCellWithReuseIdentifier:topIndentifer forIndexPath:indexPath];
        topCell.backgroundColor = [UIColor clearColor];
        NSArray * nameArray = @[@"石材一条街",@"天天石材展",@"工程招投标",@"金融服务",@"行业资讯",@"关于我们",@"联系我们",@"更多"];
        topCell.label.text = nameArray[indexPath.row];
        topCell.image.image = [UIImage imageNamed:[NSString stringWithFormat:@"HomePage%ld",3+indexPath.row]];
        return topCell;
    }else if(collectionView == _bottomCollectionView){
        bottomCollectionViewCell * bottomCell = [collectionView dequeueReusableCellWithReuseIdentifier:bottomIndentifer forIndexPath:indexPath];
        bottomCell.backgroundColor = [UIColor clearColor];
        NSString * image = [NSString stringWithFormat:@"%@",_companyArray[indexPath.row][@"mstoImage"]];
        if (image.length>0) {
            [bottomCell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        return bottomCell;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (![Common getLoginStatus] &&(indexPath.row == 0||indexPath.row==1||indexPath.row==2||indexPath.row==3||indexPath.row==4)) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }

    NSInteger userType = [[Common getLoginInfo][@"userType"]integerValue];
    if (collectionView == _topCollectionView) {
        if (indexPath.row == 0) {
            if (userType == 9||userType==10||userType==11) {
                [self showAlertView];
            }else{
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            UIViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"StoneStreet"];
            [[Common getNavigation]pushViewController:page];
            }
        }else if (indexPath.row == 1){
            if (userType == 1||userType == 3||userType == 4||userType == 5||userType == 6||userType == 9||userType==10||userType==11) {
                [self showAlertView];
            }else{
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            UIViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"StoneShow"];
            [[Common getNavigation]pushViewController:page];
            }
        }else if (indexPath.row == 2){
            if (userType == 1||userType == 3||userType == 9||userType==10||userType==11) {
                [self showAlertView];
            }else{
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            UIViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"ProjectBids"];
            [[Common getNavigation]pushViewController:page];
            }
        }else if (indexPath.row == 3){
            if (userType == 1||userType == 4||userType == 5||userType==6||userType==12) {
                [self showAlertView];
            }else{
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            UIViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"FinancialService"];
            [[Common getNavigation]pushViewController:page];
            }
        }else if (indexPath.row == 4){
            if (userType==12) {
                [self showAlertView];
            }else{
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            UIViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"BusinessInfo"];
            [[Common getNavigation]pushViewController:page];
            }
        }else if (indexPath.row == 5){
            if (userType==12) {
                [self showAlertView];
            }else{
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"PersonalStoryboard" bundle:nil];
            UIViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"AboutUs"];
            [[Common getNavigation]pushViewController:page];
            }
        }else if (indexPath.row == 6){
            if (userType==12) {
                [self showAlertView];
            }else{
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            UIViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"ConnectUs"];
            [[Common getNavigation]pushViewController:page];
            }
        } else if (indexPath.row == 7){
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
            UIViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"MoreStone"];
            [[Common getNavigation]pushViewController:page];
        }
    }else{
        if (userType == 9||userType==10||userType==11) {
            [self showAlertView];
        }else{
        UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        StoneStreetStoreDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"StoneStreetStoreDetail"];
        page.storeId = _companyArray[indexPath.row][@"mstoId"];
        [[Common getNavigation]pushViewController:page];
        }
    }
}


- (void)showAlertView{
    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"对不起，您无权访问该版块" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPages
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 155), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_imageArray[index][@"titleimg"]]] placeholderImage:[UIImage imageNamed:@"beijing"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_scroView.header endRefreshing];
    [_bottomCollectionView.header endRefreshing];
    if (tag == GS_GS_queryAdvertismentById) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            self.imageArray = database[@"result"];
            
            self.headerScroll.delegate=self;
            self.headerScroll.datasource=self;
            [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];
        }
        
    }else if (tag == GS_GS_queryMallStoreRECList){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.bottomCollectionView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.bottomCollectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.companyArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"stores"];
                for (id entity in arr) {
                    [self.companyArray addObject:entity];
                }
                
                [_bottomCollectionView reloadData];
                
            });
            
            
        }
        
    }

}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_scroView.header endRefreshing];
    [_bottomCollectionView.header endRefreshing];
    [self dismissWaitDialog];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
